package com.control;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.entity.FileComp;
import hyl.core.MyFun;
import hyl.core.info.Content;
//不可少  @MultipartConfig

@MultipartConfig(location = "upload", fileSizeThreshold = 0, maxFileSize = 5242880, // 5 MB
		maxRequestSize = 20971520)
//  /和/*都拦截静态资源，都匹配未匹配上的servlet，但是/*会拦截*.jsp，而/会放行*.jsp。
@WebServlet(name = "UploadControl", urlPatterns = "/upload")
public class UploadTomcat extends HttpServlet {
	// private static final MultipartConfigElement MULTI_PART_CONFIG = new
	// MultipartConfigElement("");

	private static final long serialVersionUID = 1L;
	public static final Logger Log = LoggerFactory.getLogger(UploadTomcat.class);

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("application/json; charset=utf-8");
		PrintWriter writer = resp.getWriter();
		Content ct = new Content();
		// 存储路径
		// 上传单个文件
		// 验证码
		String code = req.getParameter("c");
		// 系统名称
		String sysname = req.getParameter("s");
		// 分组
		String 前缀 = req.getParameter("g1");
		// 对象
		String 后缀 = req.getParameter("g2");
		// 文件名命名方式 0原名 1 uuid 2时间 3时间戳
		int type = MyFun.str2int(req.getParameter("t"));
		// 是否安全 下载 0:无 1要
		int isauth = MyFun.str2int(req.getParameter("a"));
		Log.info("c=" + code + ",s=" + sysname + ",g1=" + 前缀 + ",g2=" + 后缀 + ",t=" + type);
		// 上传验证码正确允许长传
		if (MyFun.isEmpty(code) || !FileComp.UPLOADCHECKCODE.equals(code)) {
			ct.setCode(0, "验证码错误");
			writer.write(ct.toJsonString());
			writer.flush();
			writer.close();
			return;
		}
		// Servlet3.0将multipart/form-data的POST请求封装成Part，通过Part对上传的文件进行操作。
		// 通过表单file控件(<input type="file" name="file">)的名字直接获取Part对象
		// Servlet3没有提供直接获取文件名的方法,需要从请求头中解析出来
		// 获取请求头，请求头的格式：form-data; name="file"; filename="demo.zip"
		// String contentType = req.getContentType();
		// if (contentType != null && contentType.startsWith("multipart/"))
		// req.setAttribute("org.eclipse.jetty.multipartConfig", new
		// MultipartConfigElement(""));

		/*
		 * req.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, MULTI_PART_CONFIG);
		 * for(Part part: request.getParts()) { ... } ; } else { ... }
		 */
		String msg = FileComp.upload(req, sysname, 前缀, 后缀, type, isauth);
		
		if (msg.startsWith("["))
			ct.setCode(1, msg);
		else {
			ct.setCode(0, msg);
		}
		writer.write(ct.toJsonString());
		writer.flush();
		writer.close();
	}
}
